package com.zzu.securityKeycloak.controller;

import com.zzu.securityKeycloak.Repository.BookRepository;
import org.keycloak.KeycloakSecurityContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
public class HelloController {

    private final HttpServletRequest request;
    private final BookRepository bookRepository;

    @Autowired
    public HelloController(HttpServletRequest request, BookRepository bookRepository) {
        this.request = request;
        this.bookRepository = bookRepository;
    }

    @GetMapping(value = "/")
    public String getHome() {
        return "index";
    }

    @GetMapping(value = "/books")
    public String getBooks(Model model) {
        configCommonAttributes(model);
        model.addAttribute("books", bookRepository.readAll());
        return "books";
    }

    @GetMapping(value = "/manager")
    public String getManager(Model model) {
        configCommonAttributes(model);
        model.addAttribute("books", bookRepository.readAll());
        return "manager";
    }

    @GetMapping(value = "/logout")
    public String logout() throws ServletException {
        request.logout();
        return "redirect:/";
    }

    private void configCommonAttributes(Model model) {
        model.addAttribute("name", getKeycloakSecurityContext().getIdToken().getGivenName());
    }

    private KeycloakSecurityContext getKeycloakSecurityContext() {
        return (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
    }

    /**
     * 在控制器中获取用户，在@Controller 注解的bean里，有额外的选项。principal 可以直接作为方法参数，框架会自动注入。
     * @return
     */
    @RequestMapping(value = "/userinfo", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getuserInfo(Principal principal) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("username", principal.getName());
        System.out.println("Debug: the username is " + principal.getName());
        return map;
    }

    /**
     * 从keycloak得到登陆用户信息
     * @param req
     * @param response
     * @return
     */
//    @ApiOperation(value="从keycloak得到登陆用户信息", notes = "从keycloak得到登陆用户信息")
    @RequestMapping(value = "/keycloakuserinfo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> userinfo(HttpServletRequest req, HttpServletResponse response) {

        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<String> roles = new ArrayList<String>();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //首先检查是否存在认证用户
        if (!(authentication instanceof AnonymousAuthenticationToken)) {

            for (GrantedAuthority grantedAuthority: authentication.getAuthorities()) {
                roles.add(grantedAuthority.getAuthority());
            }

            resultMap.put("roles", roles.toString());
            resultMap.put("username", authentication.getName());
        }

        return resultMap;
    }


    @RequestMapping(value = "/user", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String customer(HttpServletRequest request) {
        KeycloakSecurityContext keycloak = (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
        return "customer :: " + keycloak.getTokenString();
    }

    @RequestMapping(value = "/admin", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String admin(HttpServletRequest request) {
        KeycloakSecurityContext keycloak = (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
        return "admin :: " + keycloak.getTokenString();
    }

    /*@RequestMapping(value = "/logout", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String logout(HttpServletRequest request) {
        try {
            request.logout();
            return "logout success";
        } catch (ServletException e) {
            return "logout fail";
        }
    }*/

}
